import React, { useState, useEffect } from 'react'
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Tag,
  Row,
  Col,
  DatePicker,
  Switch,
  Tree,
  Layout,
  Typography,
  Divider
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  TeamOutlined,
  ApartmentOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import type { TreeDataNode } from 'antd'
import dayjs from 'dayjs'
import type { User, UserFormData } from '@/types/user'
import type { Department } from '@/types/dept'

const { Option } = Select
const { RangePicker } = DatePicker
const { Title } = Typography

const Index: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<User[]>([])
  const [filteredData, setFilteredData] = useState<User[]>([])
  const [selectedRows, setSelectedRows] = useState<User[]>([])
  const [modalVisible, setModalVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState('新增用户')
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [selectedDept, setSelectedDept] = useState<number | null>(null)
  const [searchForm] = Form.useForm()
  const [userForm] = Form.useForm()

  // 模拟部门数据
  const departmentData: Department[] = [
    {
      id: 1,
      name: '总公司',
      code: 'ROOT',
      parentId: 0,
      children: [
        {
          id: 2,
          name: '技术研发中心',
          code: 'TECH',
          parentId: 1,
          children: [
            { id: 3, name: '前端开发部', code: 'FE', parentId: 2 },
            { id: 4, name: '后端开发部', code: 'BE', parentId: 2 },
            { id: 5, name: '测试部', code: 'QA', parentId: 2 }
          ]
        },
        {
          id: 6,
          name: '市场运营中心',
          code: 'MARKET',
          parentId: 1,
          children: [
            { id: 7, name: '市场部', code: 'MARKETING', parentId: 6 },
            { id: 8, name: '运营部', code: 'OPERATION', parentId: 6 },
            { id: 9, name: '客服部', code: 'SERVICE', parentId: 6 }
          ]
        },
        {
          id: 10,
          name: '行政管理中心',
          code: 'ADMIN',
          parentId: 1,
          children: [
            { id: 11, name: '人力资源部', code: 'HR', parentId: 10 },
            { id: 12, name: '财务部', code: 'FINANCE', parentId: 10 },
            { id: 13, name: '行政部', code: 'ADMIN', parentId: 10 }
          ]
        }
      ]
    }
  ]

  // 将部门数据转换为树形结构
  const departmentTreeData: TreeDataNode[] = departmentData.map(dept => ({
    key: dept.id,
    title: dept.name,
    icon: dept.children ? <ApartmentOutlined /> : <TeamOutlined />,
    children: dept.children?.map(child => ({
      key: child.id,
      title: child.name,
      icon: <TeamOutlined />,
      children: child.children?.map(grandChild => ({
        key: grandChild.id,
        title: grandChild.name,
        icon: <TeamOutlined />
      }))
    }))
  }))

  // 模拟用户数据
  const mockData: User[] = [
    {
      id: 1,
      username: 'admin',
      nickname: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      status: 1,
      role: '超级管理员',
      dept: '总公司',
      deptId: 1,
      createTime: '2023-01-15 10:30:00',
      lastLoginTime: '2024-01-28 15:45:00'
    },
    {
      id: 2,
      username: 'zhangsan',
      nickname: '张三',
      email: 'zhangsan@example.com',
      phone: '13900139000',
      status: 1,
      role: '普通用户',
      dept: '前端开发部',
      deptId: 3,
      createTime: '2023-03-20 14:20:00'
    },
    {
      id: 3,
      username: 'lisi',
      nickname: '李四',
      email: 'lisi@example.com',
      phone: '13700137000',
      status: 0,
      role: '普通用户',
      dept: '后端开发部',
      deptId: 4,
      createTime: '2023-05-10 09:15:00',
      lastLoginTime: '2024-01-27 16:30:00'
    },
    {
      id: 4,
      username: 'wangwu',
      nickname: '王五',
      email: 'wangwu@example.com',
      phone: '13600136000',
      status: 1,
      role: '部门经理',
      dept: '市场部',
      deptId: 7,
      createTime: '2023-07-22 11:20:00'
    },
    {
      id: 5,
      username: 'zhaoliu',
      nickname: '赵六',
      email: 'zhaoliu@example.com',
      phone: '13500135000',
      status: 1,
      role: '普通用户',
      dept: '人力资源部',
      deptId: 11,
      createTime: '2023-09-05 16:45:00'
    },
    {
      id: 6,
      username: 'admin',
      nickname: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      status: 1,
      role: '超级管理员',
      dept: '总公司',
      deptId: 1,
      createTime: '2023-01-15 10:30:00',
      lastLoginTime: '2024-01-28 15:45:00'
    },
    {
      id: 7,
      username: 'zhangsan',
      nickname: '张三',
      email: 'zhangsan@example.com',
      phone: '13900139000',
      status: 1,
      role: '普通用户',
      dept: '前端开发部',
      deptId: 3,
      createTime: '2023-03-20 14:20:00'
    },
    {
      id: 8,
      username: 'lisi',
      nickname: '李四',
      email: 'lisi@example.com',
      phone: '13700137000',
      status: 0,
      role: '普通用户',
      dept: '后端开发部',
      deptId: 4,
      createTime: '2023-05-10 09:15:00',
      lastLoginTime: '2024-01-27 16:30:00'
    },
    {
      id: 9,
      username: 'wangwu',
      nickname: '王五',
      email: 'wangwu@example.com',
      phone: '13600136000',
      status: 1,
      role: '部门经理',
      dept: '市场部',
      deptId: 7,
      createTime: '2023-07-22 11:20:00'
    },
    {
      id: 10,
      username: 'zhaoliu',
      nickname: '赵六',
      email: 'zhaoliu@example.com',
      phone: '13500135000',
      status: 1,
      role: '普通用户',
      dept: '人力资源部',
      deptId: 11,
      createTime: '2023-09-05 16:45:00'
    }
  ]

  // 加载数据
  const loadData = async () => {
    setLoading(true)
    try {
      // 模拟API调用
      setTimeout(() => {
        setData(mockData)
        setFilteredData(mockData)
        setLoading(false)
      }, 500)
    } catch (error) {
      message.error('加载数据失败')
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  // 根据选择的部门筛选用户
  const filterUsersByDept = (deptId: number | null) => {
    if (deptId === null) {
      setFilteredData(data)
    } else {
      const filtered = data.filter(user => user.deptId === deptId)
      setFilteredData(filtered)
    }
  }

  // 部门树选择事件
  const onDeptSelect = (selectedKeys: React.Key[]) => {
    if (selectedKeys.length > 0) {
      const deptId = selectedKeys[0] as number
      setSelectedDept(deptId)
      filterUsersByDept(deptId)
    } else {
      setSelectedDept(null)
      setFilteredData(data)
    }
  }

  // 获取所有部门选项（用于表单选择）
  const getAllDepartments = (depts: Department[]): Department[] => {
    let allDepts: Department[] = []
    depts.forEach(dept => {
      allDepts.push({
        id: dept.id,
        name: dept.name,
        code: dept.code,
        parentId: dept.parentId
      })
      if (dept.children) {
        allDepts = [...allDepts, ...getAllDepartments(dept.children)]
      }
    })
    return allDepts
  }

  const allDepartments = getAllDepartments(departmentData)

  // 表格列配置
  const columns: ColumnsType<User> = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center'
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 120
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 150
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120
    },
    {
      title: '部门',
      dataIndex: 'dept',
      key: 'dept',
      width: 120
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (role: string) => (
        <Tag
          color={
            role === '超级管理员'
              ? 'red'
              : role === '部门经理'
                ? 'orange'
                : 'blue'
          }
        >
          {role}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 150,
      render: (time?: string) =>
        time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '从未登录'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size='small'>
          <Button
            type='link'
            size='small'
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title='确定要删除这个用户吗？'
            onConfirm={() => handleDelete(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' size='small' danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 搜索处理
  const handleSearch = (values: any) => {
    console.log('搜索参数:', values)
    let filtered = data

    if (selectedDept) {
      filtered = filtered.filter(user => user.deptId === selectedDept)
    }

    if (values.keyword) {
      const keyword = values.keyword.toLowerCase()
      filtered = filtered.filter(
        user =>
          user.username.toLowerCase().includes(keyword) ||
          user.nickname.toLowerCase().includes(keyword) ||
          user.email.toLowerCase().includes(keyword)
      )
    }

    if (values.status) {
      filtered = filtered.filter(user => user.status === values.status)
    }

    setFilteredData(filtered)
  }

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields()
    setSelectedDept(null)
    setFilteredData(data)
  }

  // 新增用户
  const handleAdd = () => {
    setModalTitle('新增用户')
    setEditingUser(null)
    userForm.resetFields()
    setModalVisible(true)
  }

  // 编辑用户
  const handleEdit = (record: User) => {
    setModalTitle('编辑用户')
    setEditingUser(record)
    userForm.setFieldsValue({
      ...record,
      deptId: record.deptId,
      status: record.status === 1
    })
    setModalVisible(true)
  }

  // 删除用户
  const handleDelete = async (id: number) => {
    try {
      const newData = data.filter(item => item.id !== id)
      setData(newData)
      setFilteredData(
        newData.filter(user =>
          selectedDept ? user.deptId === selectedDept : true
        )
      )
      message.success('删除成功')
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRows.length === 0) {
      message.warning('请选择要删除的用户')
      return
    }

    try {
      const ids = selectedRows.map(row => row.id)
      const newData = data.filter(item => !ids.includes(item.id))
      setData(newData)
      setFilteredData(
        newData.filter(user =>
          selectedDept ? user.deptId === selectedDept : true
        )
      )
      setSelectedRows([])
      message.success('批量删除成功')
    } catch (error) {
      message.error('批量删除失败')
    }
  }

  // 提交表单
  const handleSubmit = async (values: any) => {
    try {
      const formData: UserFormData = {
        ...values,
        status: values.status ? 1 : 0
      }

      if (editingUser) {
        // 编辑操作
        const selectedDept = allDepartments.find(
          dept => dept.id === values.deptId
        )
        const updatedUser: User = {
          ...editingUser,
          ...formData,
          dept: selectedDept?.name || editingUser.dept
        }

        const newData = data.map(item =>
          item.id === editingUser.id ? updatedUser : item
        )

        setData(newData)
        setFilteredData(
          newData.filter(user =>
            selectedDept ? user.deptId === selectedDept : true
          )
        )
        message.success('编辑成功')
      } else {
        // 新增操作
        const selectedDept = allDepartments.find(
          dept => dept.id === values.deptId
        )
        const newUser: User = {
          id: Math.max(...data.map(item => item.id)) + 1,
          ...formData,
          dept: selectedDept?.name || '',
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }

        const newData = [...data, newUser]
        setData(newData)
        setFilteredData(
          newData.filter(user =>
            selectedDept ? user.deptId === selectedDept : true
          )
        )
        message.success('新增成功')
      }

      setModalVisible(false)
      userForm.resetFields()
    } catch (error) {
      message.error('操作失败')
    }
  }

  // 行选择配置
  const rowSelection = {
    selectedRowKeys: selectedRows.map(row => row.id),
    onChange: (_: React.Key[], selectedRows: User[]) => {
      setSelectedRows(selectedRows)
    }
  }

  return (
    <div
      style={{
        height: '100%',
        background: '#fff',
        display: 'flex'
      }}
    >
      <div
        style={{ width: 220, borderRight: '1px solid #f0f0f0', padding: 12 }}
      >
        <Title level={4}>
          <ApartmentOutlined /> 部门组织
        </Title>
        <Input
          placeholder='请输入部门名称'
          style={{ marginBottom: '16px', marginTop: '16px' }}
        />
        <Tree
          treeData={departmentTreeData}
          defaultExpandedKeys={[1, 2, 6, 10]}
          defaultSelectedKeys={[1]}
          onSelect={onDeptSelect}
          showIcon
          blockNode
          style={{ padding: '8px 0' }}
        />
      </div>
      <div style={{ flex: 1, paddingLeft: 12 }}>
        {/* 搜索区域 */}
        <Form form={searchForm} layout='vertical' onFinish={handleSearch}>
          <Row gutter={[16, 0]}>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name='keyword' label='关键词'>
                <Input placeholder='请输入用户名/昵称/邮箱' />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name='status' label='状态'>
                <Select placeholder='请选择状态' allowClear>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Form.Item name='createTime' label='创建时间'>
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Form.Item label=' '>
                <Space>
                  <Button
                    type='primary'
                    icon={<SearchOutlined />}
                    htmlType='submit'
                  >
                    搜索
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={handleReset}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        {/* 操作按钮区域 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type='primary' icon={<PlusOutlined />} onClick={handleAdd}>
              新增用户
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
              disabled={selectedRows.length === 0}
            >
              批量删除
            </Button>
            <span>已选择 {selectedRows.length} 项</span>
          </Space>
        </div>

        {/* 表格区域 */}
        <Table
          size='small'
          columns={columns}
          dataSource={filteredData}
          rowKey='id'
          loading={loading}
          scroll={{ x: 1200 }}
          rowSelection={rowSelection}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`
          }}
        />
      </div>
      <Modal
        title={modalTitle}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form form={userForm} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name='username'
                label='用户名'
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' }
                ]}
              >
                <Input prefix={<UserOutlined />} placeholder='请输入用户名' />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name='nickname'
                label='昵称'
                rules={[{ required: true, message: '请输入昵称' }]}
              >
                <Input placeholder='请输入昵称' />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name='email'
                label='邮箱'
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '邮箱格式不正确' }
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder='请输入邮箱' />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name='phone'
                label='手机号'
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
                ]}
              >
                <Input prefix={<PhoneOutlined />} placeholder='请输入手机号' />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name='deptId'
                label='部门'
                rules={[{ required: true, message: '请选择部门' }]}
              >
                <Select placeholder='请选择部门'>
                  {allDepartments.map(dept => (
                    <Option key={dept.id} value={dept.id}>
                      {dept.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name='role'
                label='角色'
                rules={[{ required: true, message: '请选择角色' }]}
              >
                <Select placeholder='请选择角色'>
                  <Option value='超级管理员'>超级管理员</Option>
                  <Option value='部门经理'>部门经理</Option>
                  <Option value='普通用户'>普通用户</Option>
                  <Option value='访客'>访客</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name='status' label='状态' valuePropName='checked'>
            <Switch checkedChildren='启用' unCheckedChildren='禁用' />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index
